import os
import shutil
import psutil


def find_processes_using_file(file_path):
    """Find processes using a given file."""
    for proc in psutil.process_iter(['pid', 'name']):
        try:
            flist = proc.open_files()
            if flist:
                for nt in flist:
                    if nt.path == file_path:
                        return proc.info['pid']
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return None


def kill_process(pid):
    """Kill a process by PID."""
    try:
        p = psutil.Process(pid)
        p.terminate()
        p.wait(timeout=5)  # Wait up to 5 seconds for the process to terminate
        print(f"Killed process {pid}")
    except Exception as e:
        print(f"Failed to kill process {pid}: {e}")


def delete_folder_contents(folder_path):
    """Delete all files and subfolders in the specified folder."""
    if not os.path.exists(folder_path):
        print(f"The path {folder_path} does not exist.")
        return

    for root, dirs, files in os.walk(folder_path, topdown=False):
        for name in files:
            file_path = os.path.join(root, name)
            pid = find_processes_using_file(file_path)
            if pid:
                print(f"File {file_path} is used by process {pid}. Attempting to close it...")
                kill_process(pid)

            try:
                os.remove(file_path)
                print(f"Deleted file: {file_path}")
            except Exception as e:
                print(f"Failed to delete file {file_path}: {e}")

        for name in dirs:
            dir_path = os.path.join(root, name)
            try:
                shutil.rmtree(dir_path)
                print(f"Deleted directory: {dir_path}")
            except Exception as e:
                print(f"Failed to delete directory {dir_path}: {e}")


if __name__ == "__main__":
    folder_to_delete = r"C:\Users\Administrator\AppData"
    delete_folder_contents(folder_to_delete)


